package com.ysu.zyw;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.Destination;
import java.util.Date;

/**
 * Created by ZeRur on 2016/1/15.
 *
 * @author yaowu.zhang
 */
public class Producer implements Runnable {

    private int id;

    public Producer(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println("producer start...");
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context-jms-producer.xml");
        JmsTemplate jmsTemplate = applicationContext.getBean("jmsTemplate", JmsTemplate.class);
        Destination destination;
        if (id % 2 == 0)
            destination = applicationContext.getBean("queueDestination", ActiveMQQueue.class);
        else
            destination = applicationContext.getBean("topicDestination", ActiveMQTopic.class);


        for (int i = 0; i < 5; i++) {
            jmsTemplate.send(destination, session -> {
                return session.createObjectMessage(new Model(-1, "message", new Date()));
            });
            System.out.println("send message - " + i);
        }
        try {
            Thread.sleep(999999);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
